//
//  LoginView.swift
//  登录
//
//  Created by 千策万划-mini on 2025/4/28.
//

import Foundation
import FBSDKCoreKit

class LoginView: UIView {
    
    // MARK: - lazy
    lazy var viewBg: UIImageView = {
        let result = UIImageView()
        result.widthHeight = XY(355, 456)
        result.isUserInteractionEnabled = true
        result.image = UIImage(named: "icon_login_bg")
        return result
    }()
    lazy var btnClose: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(40+16*2, 40+30*2)
        result.tag = 1
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()
    lazy var labelTitle: OutlineLabel = {
        let result = OutlineLabel()
        result.resetView(
            title: "Mobile Phone Quick Login",
            textColor: COLOR_WHITE(),
            font: UIFont.customBoldFont(size: 16),
            shadowColor: UIColor(hex: "2D0084"),
            outlineColor: UIColor(hex: "2D0084")
        )
        return result
    }()
    lazy var imageInputBg: UIImageView = {
        let result = UIImageView()
        result.widthHeight = XY(275, 160)
        result.image = UIImage(named: "icon_login_input_bg")
        result.isUserInteractionEnabled = true
        return result
    }()
    lazy var btnLogin: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(163, 58)
        result.setImage(UIImage(named: "icon_login_login_btn"), for: .normal)
        result.tag = 2
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()
    lazy var imageAgreeBg: UIImageView = {
        let result = UIImageView()
        result.widthHeight = XY(282, 48)
        result.isUserInteractionEnabled = true
        result.image = UIImage(named: "icon_login_agree_bg")
        return result
    }()
    lazy var btnAgree: UIButton = {
        let result = UIButton()
        result.setImage(UIImage(named: "icon_agree_uncheck"), for: .normal)
        result.setImage(UIImage(named: "icon_agree_check"), for: .selected)
        result.isSelected = true
        result.tag = 3
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()
    lazy var labelAgree: UILabel = {
        let result = UILabel()
        result.textColor = UIColor(hex: "#2D0084")
        result.font = UIFont.customMediumFont(size: 12)
        result.numberOfLines = 0
        result.lineSpace = 3
        return result
    }()
    lazy var btnPrivacyPolicy: UIButton = {
        let result = UIButton()
        result.backgroundColor = .clear
        result.widthHeight =  XY(90, 30)
        result.tag = 5
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()
    lazy var imagePhoneBg: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(247, 44)
        result.image = UIImage(named: "icon_login_tf_bg")
        return result
    }()
    lazy var labelPhonePrefix: UILabel = {
        let result = UILabel()
        result.textColor = COLOR_DETAIL()
        result.font = UIFont.customBoldFont(size: 18)
        result.fitTitle("+63", variable: 0)
        return result
    }()
    lazy var tfPhone: UITextField = {
        let result = UITextField()
        result.placeholder = "Enter mobile phone number"
        result.font = UIFont.customMediumFont(size: 14)
        result.keyboardType = .numberPad
        result.textColor = COLOR_LABEL()
        return result
    }()
    lazy var imageCodeBg: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true;
        result.widthHeight = XY(247, 44)
        result.image = UIImage(named: "icon_login_tf_bg")
        return result
    }()
    lazy var btnCode: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(68, 34)
        result.setBackgroundImage(UIImage(named: "icon_login_code_btn"), for: .normal)
        result.tag = 4
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()
    lazy var labelCode: OutlineLabel = {
        let result = OutlineLabel()
        result.resetView(
            title: "Code",
            textColor: COLOR_WHITE(),
            font: UIFont.customBoldFont(size: 14),
            shadowColor: UIColor(hex: "2D0084"),
            outlineColor: UIColor(hex: "2D0084")
        )
        return result
    }()
    lazy var strokeTextAttributes: [NSAttributedString.Key: Any] = {
        let result: [NSAttributedString.Key: Any] = [
            .strokeColor: UIColor(hex: "#794FFF"), // 描边颜色
            .foregroundColor: UIColor.white,       // 填充色
            .strokeWidth: -1                       // 负值表示描边+填充，数值越大描边越粗
        ]
        return result
    }()
    lazy var btnTime: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(68, 34)
        result.setBackgroundImage(UIImage(named: "icon_login_time_btn"), for: .normal)
        result.setTitleColor(COLOR_WHITE(), for: .normal)
        result.titleLabel?.font = UIFont.customBoldFont(size: 14)
        result.titleLabel?.shadowColor = UIColor(hex: "#2D0084")
        result.titleLabel?.shadowOffset = CGSize(width: 0.2, height: 0.5)
        result.setAttributedTitle(NSAttributedString(string: "59s", attributes: strokeTextAttributes), for: .normal)
        result.isHidden = true
        return result
    }()
    lazy var tfCode: UITextField = {
        let result = UITextField()
        result.placeholder = "Enter confirmation code"
        result.font = UIFont.customMediumFont(size: 14)
        result.keyboardType = .numberPad
        result.textColor = COLOR_LABEL()
        return result
    }()
    
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.widthHeight = XY(SCREEN_WIDTH, SCREEN_HEIGHT)
        self.backgroundColor = UIColor(hex: "000000", alpha: 0.8)
        
        self.addSubView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 添加
    func addSubView() {
        addSubview(viewBg)
        viewBg.addSubview(btnClose)
        viewBg.addSubview(labelTitle)
        viewBg.addSubview(imageInputBg)
        
        imageInputBg.addSubview(imagePhoneBg)
        imagePhoneBg.addSubview(labelPhonePrefix)
        imagePhoneBg.addSubview(tfPhone)
        
        imageInputBg.addSubview(imageCodeBg)
        imageCodeBg.addSubview(btnCode)
        btnCode.addSubview(labelCode)
        imageCodeBg.addSubview(btnTime)
        imageCodeBg.addSubview(tfCode)
        
        viewBg.addSubview(btnLogin)
        viewBg.addSubview(imageAgreeBg)
        imageAgreeBg.addSubview(labelAgree)
        imageAgreeBg.addSubview(btnAgree)
        imageAgreeBg.addSubview(btnPrivacyPolicy)
        
        self.resetView()
    }
    
    // MARK: - 点击事件
    @objc func btnClick(_ sender: UIControl) {
        feedback()
        sender.addClickAnimate()
        switch sender.tag {
        case 1:
            hide()
            break
        case 2: // 登录
            login()
            break
        case 3: // 协议
            sender.isSelected = !sender.isSelected
            break
        case 4: // code
            getLoginCode()
            break
        case 5: // Privacy Policy
            hide()
            let vc = BaseWebVC()
            vc.webUrl = LOCAL_PRIVACY_POLICY
            vc.blockShowLogin = { [weak self] in
                guard let self = self else { return }
                self.show()
            }
            GB_Nav?.pushViewController(vc, animated: true)
            break
        default:
            break
        }
    }
    
    // 开始倒计时
    func startCountdown() {
        // 倒计时时间
        var timeOut = 59
        // 建一个全局队列，默认优先级
        let queue = DispatchQueue.global(qos: .default)

        // 创建定时器
        let timer = DispatchSource.makeTimerSource(queue: queue)
        timer.schedule(deadline: .now(), repeating: 1.0)

        timer.setEventHandler { [weak self] in
            guard let self = self else { return }
            if timeOut <= 0 {
                timer.cancel()
                DispatchQueue.main.async {
                    self.btnTime.isHidden = true
                    self.btnCode.isHidden = false
                }
            } else {
                let seconds = timeOut % 60
                let timeStr = String(format: "%02d", seconds)
                DispatchQueue.main.async {
                    self.btnTime.setAttributedTitle(NSAttributedString(string: "\(timeStr)s", attributes: self.strokeTextAttributes), for: .normal)
                    self.btnTime.sizeToFit()
                }
                timeOut -= 1
            }
        }
        timer.resume()
    }
    
    // 显示
    func show() {
        if let window = WindowManager.shared.getCurrentWindow() {
            window.endEditing(true)
            // 设置初始状态（比如从底部开始）
            alpha = 0
            viewBg.transform = CGAffineTransform(translationX: 0, y: 50)
            window.addSubview(self)
            // 添加弹出动画
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
                self.alpha = 1
                self.viewBg.transform = .identity
                self.requestGoogleMarket()
            }
        }
    }

    
    
    // 隐藏
    func hide() {
        // 添加消失动画
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
            self.alpha = 0
            self.viewBg.transform = CGAffineTransform(translationX: 0, y: 50)
        } completion: { _ in
            self.removeFromSuperview()
            // 重置 transform，以便下次显示
            self.viewBg.transform = .identity
        }
    }
    
    // MARK: - 重置界面
    func resetView() {
        viewBg.centerXCenterY = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT/2)
        btnClose.rightTop = XY(viewBg.width, 0)
        labelTitle.centerXTop = XY(viewBg.width/2, 100+3)
        imageInputBg.centerXTop = XY(viewBg.width/2, labelTitle.bottom+6)
        btnLogin.centerXTop = XY(imageInputBg.centerX, imageInputBg.bottom+12)
        imageAgreeBg.centerXTop = XY(btnLogin.centerX, btnLogin.bottom+15)
        
        // 输入框
        imagePhoneBg.centerXTop = XY(imageInputBg.width/2, 25)
        labelPhonePrefix.leftCenterY = XY(12, imagePhoneBg.height/2)
        tfPhone.widthHeight = XY(imagePhoneBg.width-labelPhonePrefix.right-8*2, imagePhoneBg.height-10)
        tfPhone.leftCenterY = XY(labelPhonePrefix.right+8, labelPhonePrefix.centerY)
        
        imageCodeBg.centerXBottom = XY(imageInputBg.width/2, imageInputBg.height-25)
        btnCode.rightCenterY = XY(imageCodeBg.width-7, imageCodeBg.height/2)
        labelCode.centerXCenterY = XY(btnCode.width/2, btnCode.height/2)
        btnTime.centerXCenterY = btnCode.centerXCenterY
        tfCode.widthHeight = XY(btnCode.left-10, imageCodeBg.height-10)
        tfCode.leftCenterY = XY(12, imageCodeBg.height/2)
        
        let text = "I have read the Privacy Policy and understand \nthe relevant terms."
        let underlineText = "Privacy Policy"
        labelAgree.width = imageAgreeBg.width
        let attributedString = NSMutableAttributedString(string: text)
        // 查找需要下划线的文字范围
        if let range = text.range(of: underlineText) {
            let nsRange = NSRange(range, in: text)
            attributedString.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: nsRange)
            attributedString.addAttribute(.foregroundColor, value: UIColor.white, range: nsRange) // 可选：设置下划线文字颜色
        }
        labelAgree.attributedText = attributedString
        labelAgree.sizeToFit()
        labelAgree.leftCenterY = XY(31, imageAgreeBg.height/2)
        
        btnPrivacyPolicy.leftTop = XY(100, 0)
        
        btnAgree.widthHeight = XY(18+10*2, imageAgreeBg.height)
        btnAgree.leftTop = XY(0, 0)
    }
    
    
    // MARK: - request
    // 获取验证码
    func getLoginCode() {
        if(!isStr(tfPhone.text)){
            GlobalMethod.showAlert(strAlert: "Please enter your phone number")
            return;
        }
        // 记录点击发送验证码的时间
        GlobalMethod.writeStr(GlobalMethod.getTimeStamp(), forKey: LOCAL_SMS_SEND_TIME)
        
//        // google market上报
//        if GlobalMethod.readBoolFromUserDefaults(forKey: LOCAL_AUTHCODR_GOOGLE_MARKET) == false {
//            GlobalMethod.writeBool(true, forKey: LOCAL_AUTHCODR_GOOGLE_MARKET)
//
//        }
        
        LoginRequestApi.getLoginCode(phone: UnPackStr(tfPhone.text?.removeAllSpaces())) { request, responseData in
            GlobalMethod.showAlert(strAlert: "SMS send successfully", time: 3)
            self.btnCode.isHidden = true
            self.btnTime.isHidden = false
            self.startCountdown()
            
        } failure: { request, error in
            
        }
    }
    
    // 登录
    func login() {
        if(!isStr(tfPhone.text)){
            GlobalMethod.showAlert(strAlert: "Please enter your phone number")
            return;
        }
        if(!isStr(tfCode.text)){
            GlobalMethod.showAlert(strAlert: "Please enter the verification code")
            return;
        }
        if btnAgree.isSelected == false {
            GlobalMethod.showAlert(strAlert: "Please read the above carefully")
            return
        }
        LoginRequestApi.login(phone: UnPackStr(tfPhone.text?.removeAllSpaces()), code: (tfCode.text?.removeAllSpaces() ?? "")) { request, responseData in
            // 记录登录成功的时间
            GlobalMethod.writeStr(UnPackStr(GlobalMethod.getTimeStamp()), forKey: LOCAL_LOGIN_SUCCESS_TIME)
            guard let res = responseData as? [String: Any] else {return}
            if let model = ModelUser.deserialize(from: res) {
                // 保存用户信息
                GlobalData.sharedInstance.GB_UserModel = model
                GlobalMethod.writeUnprefixedStr(GlobalData.sharedInstance.GB_UserModel?.cap ?? "", forKey: LOCAL_PHONE)
                GlobalData.sharedInstance.GB_SessionID = GlobalData.sharedInstance.GB_UserModel?.places
                // 发送通知
                NotificationCenter.default.post(name: Notification.Name(NOTICE_LOGIN_SUCCESS), object: nil)
                self.hide()
            }
        } failure: { request, error in
            
        }
    }
    
    // Google Market上报 - 获取 faceBook 配置
    func requestGoogleMarket() {
        if GlobalMethod.readBoolFromUserDefaults(forKey: LOCAL_LOGIN_GOOGLE_MARKET, isPrefixed: false) == false {
            GlobalMethod.writeBool(true, forKey: LOCAL_LOGIN_GOOGLE_MARKET, isPrefixed: false)
            HomeRequestApi.getFaceBookConfig { request, responseData in
                guard let res = responseData as? [String: Any] else {return}
                if let model = ModelFaceBook.deserialize(from: res) {
                    Settings.shared.appID = model.insideasedfqw.doors
                    Settings.shared.clientToken = model.insideasedfqw.scolded
                    Settings.shared.displayName = model.insideasedfqw.scolds
                    Settings.shared.appURLSchemeSuffix = model.insideasedfqw.ledge
                    ApplicationDelegate.shared.application(UIApplication.shared,didFinishLaunchingWithOptions: nil)
                }
            } failure: { request, error in
                
            }
        }
    }
}
